package controller.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import factory.UserFactory;
import pojo.User;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			UserDao userDao = UserFactory.getInstance("userdaoimpl", UserDao.class);
			String uname = request.getParameter("uname");
			String upwd = request.getParameter("upwd");
			String uphone = request.getParameter("uphone");
			String uemail = request.getParameter("uemail");
			String umessage = request.getParameter("umessage");
			String upic = request.getParameter("upic");
			User user = new User(uname, upwd, uphone, uemail, umessage, upic);
			PrintWriter out = response.getWriter();
			if(userDao.saveUser(user) == 1) {
//				request.getRequestDispatcher("view/showRegisterMess.jsp").forward(request, response);
				request.getRequestDispatcher("view/index.jsp").forward(request, response);
			}else {
				out.println("<script>alert('注册失败,用户名重复!');history.back();</script>") ;
			}
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}